package fr.afcepf.ai89.esharing.data;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import fr.afcepf.ai89.esharing.entity.Aem;
import fr.afcepf.ai89.esharing.entity.PromotionAem;
import fr.afcepf.ai89.esharing.entity.PromotionParc;

@Stateless
public class DAOPromotionAem implements IDAOPromotionAem {

	@PersistenceContext(unitName = "ESharingPhase22")
	EntityManager em;

	@Override
	public PromotionAem getPromoAem(int idPromoAem) {
		Query hql = em
				.createQuery("SELECT promo FROM PromotionAem promo WHERE promo.idPromotionAem = :idPromo");
		hql.setParameter("idPromo", idPromoAem);
		return (PromotionAem) hql.getSingleResult();
	}

	@Override
	public List<PromotionAem> getPromosAem() {
		Query hql = em.createQuery("SELECT promo FROM PromotionAem");
		return hql.getResultList();
	}

	@Override
	public List<PromotionAem> getPromosAem(Aem aem) {
		Query hql = em
				.createQuery("SELECT promo FROM PromotionAem promo INNER JOIN FETCH promo.aem WHERE promo.aem = :aem");
		hql.setParameter("aem", aem);
		List<PromotionAem> promos = hql.getResultList();
		return promos;
	}

	@Override
	public int promouvoirAem(PromotionAem promoAem) {
		em.persist(promoAem);

		Query hql = em
				.createQuery("SELECT MAX(idPromotionAem) FROM PromotionAem promo");
		int idPormo = (Integer) hql.getSingleResult();

		return idPormo;
	}

	@Override
	public int majPromoAem(PromotionAem promoAem) {
		PromotionAem newPromoAem = em.find(PromotionAem.class, promoAem.getIdPromotionAem());
		newPromoAem.setAem(promoAem.getAem());
		newPromoAem.setDateDebutPromotionAem(promoAem.getDateDebutPromotionAem());
		newPromoAem.setDateFinPromotionAem(promoAem.getDateFinPromotionAem());
		newPromoAem.setNomPromotionAem(promoAem.getNomPromotionAem());
		newPromoAem.setPourcentReducAem(promoAem.getPourcentReducAem());
		newPromoAem.setRaisonPromotionAem(promoAem.getRaisonPromotionAem());
		em.merge(newPromoAem);
		return promoAem.getIdPromotionAem();
	}

}
